<template>
    <div class="map">

        <div id="map-wrap"></div>
        


        
        <!-- <div class="" style="position: absolute; z-index: 99999; width:100%; left:0; top: 0; background: #fff">
            定位:{{locateMarker.LatLng}}
            定位:新{{locateMarker.LatLngNew}}
        </div> -->
        <!-- 搜索菜单弹窗 and 按钮 -->
        <i class="btn-search iconfont iconxingtaiduICON_sousuo--" @click="searchMenu"></i>
        <van-popup v-model="searchShow" position="bottom" >
            <ul class="list-menu" >
                <li v-for="(item,index) in nearServices" :class="{act:item.id == searchAct}" @click="changeSrarch(item.id)" :key="item.id"><i clsss="iconfont" :style="{'backgroundImage':'url('+(item.id == searchAct?item.select_icon:item.icon)+')'}"></i>{{item.name}}</li>
                <!-- <li class="act"><i class="iconfont iconjingdian"></i>景点</li>
                <li><i class="iconfont iconmeishi"></i>美食</li> -->
            </ul>
        </van-popup>
        <i class="btn-search2 iconfont" :class="currentIcon"  @click="closeAutoBobao"></i>
    </div>
</template>

<script>
import { GPS } from '@/common/js/common'

import {Toast } from 'vant'

export default {
    name: 'Map',
    props:{
        mapData:{
            type:Object,
            default:null
        },
        lineId:{
            type:Number,
            default:null
        }
    },
    data () {
        return {
            auto_bobao_tc: true,
            currentIcon: 'iconjieshuo', // 初始图标
            // 点聚合对象
            markers: L.markerClusterGroup({
                spiderfyOnMaxZoom:true,
                maxClusterRadius:20,
                removeOutsideVisibleBounds:true,
                spiderLegPolylineOptions:{opacity:0},
                // spiderfyOnMaxZoom:false,
                iconCreateFunction: this.markersStyle
            }),
            searchAct:null,
            searchShow:false,
            autoBoBao:true,
            locateMarker:{
                LatLng:null,
                LatLngNew:null,
                Circle:null,
                marker:null
            },
            mapD:null,
            nearServices:null,

            nearServicesMarkers:{},
            lines:null,
            lines2:null,

            points:[],
            popupShow:false,
        }
    },
    mounted() {
        // console.log(this.nearServices)
        
            
        this.$nextTick(() => {
            // console.log(this.$toast)
            // console.log( this.mapData.nearServices)
            this.nearServices = this.mapData.nearServices
            this.searchAct = this.nearServices[0].id

            // 地图初始化
            this.mapInit()

            // 创建标点 并添加进点聚合
            this.markerCreate(this.mapData.scenics)
     
        })


    },
    watch:{
        lineId(newValue, oldValue) { //x线路切换
            // console.log(newValue == oldValue)
            let linesP
            if(newValue == 9999){
                this.lines2.removeFrom(this.mapD)
                this.lines.removeFrom(this.mapD)
            }else{
                linesP=eval(this.mapData.ways[newValue].latlng_list)
                if(this.lines != null){
                    console.log(1)
                    this.lines2.removeFrom(this.mapD)
                    this.lines2.setLatLngs(linesP)
                    this.lines2.addTo(this.mapD)
                    this.lines.removeFrom(this.mapD)
                    this.lines.setLatLngs(linesP)
                    this.lines.addTo(this.mapD)
                }else{
                    this.lines2 =new L.polyline(linesP,{color:'#fff',weight:10})
                    this.lines2.addTo(this.mapD)
                    this.lines =new L.polyline(linesP,{color:'green',weight:6})
                    this.lines.addTo(this.mapD)
                }
            }
            
        }

    },
    methods:{
        mapInit (){
            // 创建地图
            // console.log(this.mapData.latlng)
            let center = this.mapData.map.latlng.split(",")
            this.mapD = L.map('map-wrap', {
                center: center,
                minZoom: 6,
                maxZoom: 18,
                bounceAtZoomLimits:false,
                zoom: 14
            })

            // this.mapD =map
            //创建图层 
            L.tileLayer('https://wprd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scl=1&style=7&x={x}&y={y}&z={z}',{subdomains: '1234',maxZoom: 18,detectRetina:true}).addTo(this.mapD);
            L.tileLayer(this.mapData.map.tile_url+'/{z}/tile-{x}_{y}.png',{maxZoom: 18,detectRetina:true}).addTo(this.mapD)

            // this.mapD.zoomend({
            //     alert('123')
            // })


            // 定位
            this.mapD.locate({
              setView: false,
              watch: true,
              enableHighAccuracy: true
            })
            this.mapD.on('locationfound', this.locateM )
            this.mapD.on('locationerror', function(e) {
              // alert('定位出错=====>', e.message);
            })
        },
        locateM (e){  // 定位坐标
            let radius = e.accuracy / 2
            // alert('1:'+e.latlng)
            this.locateMarker.LatLngNew=e.latlng
            let latlng = GPS.gcj_encrypt( this.locateMarker.LatLngNew.lat, this.locateMarker.LatLngNew.lng)
            this.locateMarker.LatLngNew = L.latLng(latlng.lat, latlng.lon)

            if(this.locateMarker.LatLng != null ){
                if( this.locateMarker.LatLng != this.locateMarker.LatLngNew ){
                    // alert(1)
                    this.locateMarker.LatLng = this.locateMarker.LatLngNew
                    this.locateMarker.Circle.setLatLng(this.locateMarker.LatLngNew)
                    this.locateMarker.marker.setLatLng(this.locateMarker.LatLngNew)
                }
            }else {
                this.locateMarker.LatLng = this.locateMarker.LatLngNew
                // latlng = L.latLng(latlng.lat, latlng.lon)

                // 画圆
                this.locateMarker.Circle = L.circle(this.locateMarker.LatLngNew, {radius:radius,weight:'1'})
                this.locateMarker.Circle.addTo(this.mapD)
                // 标点
                let mk=L.divIcon({html:'<i class="icon-marker icon-marker-locate"></i>',className: 'locate-mk',iconSize: [26, 33],iconAnchor:[13,31]})
                this.locateMarker.marker = L.marker(this.locateMarker.LatLngNew, {icon:mk })
                this.locateMarker.marker.addTo(this.mapD)
            }
            if(this.autoBoBao){
                this.daoDaJingDianBoBao()
            }
        },
        daoDaJingDianBoBao(){
            var addressPoints = this.mapData.scenics
            let disList = []
            for (let i = 0; i < addressPoints.length; i++) {
                let latlng = addressPoints[i].latlng.split(",")
                let gLatLng = new L.LatLng(latlng[0],latlng[1])
                var dis = this.locateMarker.LatLngNew.distanceTo(gLatLng)
                disList.push(dis)
            }
            const minIndex = disList.reduce((minIdx, current, idx) => 
            current < disList[minIdx] ? idx : minIdx, 0);
            let auto_bobao_juli = this.mapData.auto_bobao_juli
            if(auto_bobao_juli !== '' && !isNaN(auto_bobao_juli)) {
                if(disList[minIndex] < auto_bobao_juli) {
                    this.$emit('sendPlayId2',minIndex)
                }else{
                    this.$emit('sendPlayId3')
                    if (this.auto_bobao_tc) {
                        Toast('自动播报距离为'+auto_bobao_juli+'米，目前距离最近的景点'+Math.round(disList[minIndex])+'米')
                        this.auto_bobao_tc = false
                    }
                }
            }
            
            
        },
        // 点聚合样式
        markersStyle (cluster) {
            let tit=cluster.getAllChildMarkers()
            // console.log(tit[0].options.icon.options.tit)
            return L.divIcon({ html: '<i><b>' + cluster.getChildCount() + '</b></i><p class="text-wrap"><span class="text-tit">'+tit[0].options.icon.options.tit+'等</span></p>', className: 'mycluster', iconSize: [26,33],iconAnchor:[13,33]  })
        },
        //方法：创建标点添加进点聚合对象 
        markerCreate (addressPoints){
            for (let i = 0; i < addressPoints.length; i++) {
                let a = addressPoints[i]
                
                // let myIcon=this.markerIcon(a[2])
                // let marker = L.marker(new L.LatLng(a[0], a[1]), {icon: myIcon})
                let myIcon=this.markerIcon(a.name)
                let latlng = a.latlng.split(",")
                let marker = L.marker(new L.LatLng(latlng[0],latlng[1]), {icon: myIcon})
                let content='<div class="senice-popup"><div class="hd"><h3>'+a.name+'</h3></div><div class="bd"><i class="img"><img src="'+a.image+'" alt=""></i><div class="explain"><p class="introduction" id="introduction'+i+'" >'+a.content.substr(0, [25])+'...</p><div class="btns"><a href="javascript:;" class="button btn-audio-play" id="play'+i+'"><i class="icon"> </i><em>解说</em></a><a href="javascript:;" id="goto'+i+'" class="button btn-goto"><i class="iconfont iconquzheli"></i><em>去这里</em></a></div></div></div></div>'

                $('.map').on('click','#introduction'+i,() => {
                    if(this.autoBoBao){
                        this.closeAutoBobao()
                    }
                    this.$emit('sendMusicId',i)
                })

                $('.map').on('click','#play'+i,() => {
                    if(this.autoBoBao){
                        this.closeAutoBobao()
                    }
                    this.$emit('sendPlayId',i)
                })


                $('.map').on('click','#goto'+i,() => {
                    this.mapD.closePopup()
                    this.goto(marker.getLatLng())
                })

                marker.bindPopup(content)
                this.markers.addLayer(marker)
                this.mapD.addLayer(this.markers)
            }
        },
        // 创建标点样式
        markerIcon (titName,iconImg){
            // console.log(iconImg == false)
            let html
            if(iconImg != undefined ){
                html = '<i class="icon-music" style="background-image:url('+iconImg+')"></i><p class="text-wrap"><span class="text-tit">'+titName+'</span></p>'
            }else {
                html = '<i class="icon-music" ></i><p class="text-wrap"><span class="text-tit">'+titName+'</span></p>'
            }
            return L.divIcon({
                html:html,
                // iconUrl: this.icon.music,
                className: 'icon222', 
                iconSize: [26, 33],
                tit:titName,
                iconAnchor:[13,33], //图标宽度一半，图标高， 就是下中位置
                // popupAnchor:[0,0]
            });
        },
        searchMenu(){ //s搜索菜单弹窗显示
            this.searchShow=true
        },
        closeAutoBobao(){ //s搜索菜单弹窗显示
            this.currentIcon = this.currentIcon === 'iconjieshuo' ? 'iconcha1' : 'iconjieshuo';
            if (this.autoBoBao) {
                Toast('关闭自动播报')
                this.autoBoBao=false
            } else {
                Toast('开启自动播报')
                this.autoBoBao=true
            }
        },
        closeAutoBobao2(){ 
            this.currentIcon = 'iconcha1'
            this.autoBoBao=false
        },
        changeSrarch (id){//搜索菜单切换
            console.log(this.nearServices)
            if(this.searchAct != id){
                this.searchAct = id

                this.mapD.removeLayer(this.markers)
                for (let i in this.nearServicesMarkers){
                    this.mapD.removeLayer(this.nearServicesMarkers[i])
                }

                let scenicId =this.$route.query.id

                if(id == this.nearServices[0].id){
                    console.log(1)
                    this.mapD.addLayer(this.markers)
                }else if(this.nearServicesMarkers[id] == undefined){
                    console.log(2)
                    this.axios.post('/point/select',this.qs.stringify({scenic_id:scenicId,type_id:id}),{emulateJSON:true})
                        .then((response) => {
                            // console.log(response)
                            // let pointsData =

                            this.nearServicesMarkers[id] =new L.layerGroup();
                            this.servicesMarkes(response.data.data,id)
                            
                            this.mapD.addLayer(this.nearServicesMarkers[id]);
                        },(error) =>{
                            console.log(error)
                        })
                }else{
                    console.log(3)
                    // console.log('add')
                    // console.log(this.nearServicesMarkers[id])
                    this.mapD.addLayer(this.nearServicesMarkers[id]);
                    
                }

            }
            this.searchShow  = false
            
        },
        servicesMarkes(pointsData,id){
                console.log(pointsData)
            for(let i=0; i < pointsData.length; i++){
                let a = pointsData[i]
                let myIcon=this.markerIcon(a.name,a.label_icon)

                let latlng = a.latlng.split(",")
                let marker = L.marker(new L.LatLng(latlng[0],latlng[1]), {icon: myIcon})
                
                let content='<div class="near-services-popup"><i style="background-image:url('+a.marker_icon+')"></i><span id="gotose'+id+i+'">去这里</span></div>'

                $('.map').on('click','#gotose'+id+i,() => {
                    this.goto(marker.getLatLng())
                })

                marker.bindPopup(content,{closeButton:false})
                this.nearServicesMarkers[id].addLayer(marker);
                // this.markers.addLayer(marker)
            }
        },
        goto(gLatLng){
            // const toast = Toast.fail({
            //   mask: true,
            //   message: '加载中...'
            // })

            if (this.locateMarker.LatLngNew == null) {
                Toast('无法获取您的位置信息')
                // alert("无法获取您的位置信息")
                return
            }

           

            //'定位新:'  this.locateMarker.LatLngNew
            // 线路  this.mapData.ways 
            
            // 获取最近的线路
            let ways = eval(this.mapData.ways)
            // 所有路线中最小距离的集合
            let allWayMinDisList = []
            for (var i = 0; i < ways.length; i++) {
                let latlngList = eval(ways[i].latlng_list)
                let disList = []
                for (var j = 0; j < latlngList.length; j++) {
                    //console.log(i + "," +latlngList[j])

                    var latlng = L.latLng(latlngList[j][0], latlngList[j][1])
                    var dis = gLatLng.distanceTo(latlng)
                    //console.log(i+"======="+dis)
                    disList.push(dis)
                }
                allWayMinDisList.push(Math.min.apply(null, disList))
            }

            let closeWayIndex = allWayMinDisList.indexOf(Math.min.apply(null, allWayMinDisList))
            // 得到最近的路线
            let closeWay = ways[closeWayIndex]


            //alert(this.locateMarker.LatLngNew)


            // 自身位置离哪个点最近
            // 最近的路线
            let closeWayLatlngList = eval(closeWay.latlng_list)
            let originDisList = []
            let terminiDisList = []
            for (var i = 0; i < closeWayLatlngList.length; i++) {

                var latlng = L.latLng(closeWayLatlngList[i][0], closeWayLatlngList[i][1])
                originDisList.push(this.locateMarker.LatLngNew.distanceTo(latlng))
                terminiDisList.push(gLatLng.distanceTo(latlng))
            }

            // 起点距离最近路线的距离
            var originDis = Math.min.apply(null, originDisList)
            // 终点距离最近路线的距离
            var terminiDis = Math.min.apply(null, terminiDisList)

            if (originDis > 10000) {
                // 超出距离
                // 
                Toast('您不在景区')
                // alert('您不在景区')
                return
            }

            // 起点的经纬度
            var originLatlng = closeWayLatlngList[originDisList.indexOf(originDis)]

            // 终点的经纬度
            var terminiLatlng = closeWayLatlngList[terminiDisList.indexOf(terminiDis)]

            // 截取路线
            var cutCount = 0
            var goHereLatlngList = []
            for (var i = 0; i < closeWayLatlngList.length; i++) {
                if (originLatlng == closeWayLatlngList[i] || terminiLatlng == closeWayLatlngList[i]) {
                    cutCount++
                }
                if (cutCount == 1) {
                    goHereLatlngList.push(closeWayLatlngList[i])
                }
                if (cutCount == 2) {
                    goHereLatlngList.push(closeWayLatlngList[i])
                    break
                }
            }

            var aaa = [originLatlng,terminiLatlng]


            if(this.lines != null){
                this.lines2.removeFrom(this.mapD)
                this.lines2.setLatLngs(goHereLatlngList)
                this.lines2.addTo(this.mapD)
                this.lines.removeFrom(this.mapD)
                this.lines.setLatLngs(goHereLatlngList)
                this.lines.addTo(this.mapD)
            }else{
                this.lines2 =new L.polyline(goHereLatlngList,{color:'#fff',weight:10})
                this.lines2.addTo(this.mapD)
                this.lines =new L.polyline(goHereLatlngList,{color:'green',weight:6})
                this.lines.addTo(this.mapD)
            }

            // if (this.lines != null) {
            //     this.lines.setLatLngs(goHereLatlngList)
            //     this.lines2.setLatLngs(goHereLatlngList)
            // } else {
            //     this.lines =new L.polyline(goHereLatlngList,{color:'green',weight:6})
            //     this.lines.addTo(this.mapD)
            // }
        }
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style  lang="scss">
#map-wrap {height:100%;}
.leaflet-bottom.leaflet-right ,.leaflet-top.leaflet-left{display: none;}

.mycluster {
    i{ position: absolute; bottom: 0; left:50%; margin-left: -13px; width: 26px; height:33px; background: url(../assets/images/c.png) center center; background-size: 100%  100%; text-align: center;}
    b { display: block;line-height: 26px; font-size: 14px; color: orange; }
}
// 图标
.icon-music {position: absolute; bottom: 0; left:50%; margin-left: -13px; width: 26px; height:33px; background: url(../assets/images/b.png) center center; background-size: 100% 100%; }

// 定位图标
.icon-marker{position: absolute; bottom: 0; left:50%; margin-left: -13px; width: 26px; height:33px;  background-size: 100% 100%; }
.icon-marker-locate{background: url('../assets/images/a.png') center center; background-size: 100% 100%;}

.text-wrap { 
    position: absolute; bottom:-2px; text-align: center; height:0; width: 720px; left:50%; margin-left: -360px;
    .text-tit { display: inline-block;  white-space: nowrap; background: rgba(255,255,255,.7); padding: 0 1rem; height: 20px; line-height: 20px; border-radius: 10px; border: 1Px solid #ccc; }
}



// 标点弹窗
.leaflet-popup {
    bottom: 34px !important; margin-bottom: 0;margin-bottom: 10Px;
    .leaflet-popup-content-wrapper , .leaflet-popup-tip{
        color: #333;        box-shadow: 0 3Px 13Px rgba(0,0,0,.3)
    }
    .leaflet-popup-content-wrapper {       
        border-radius: 0Px; background:none;
        .leaflet-popup-content {  margin: 0;   width:100%!important;     background-color: transparent;   }
    }
    .leaflet-popup-tip-container{
        height:20px; z-index: 99; margin-top: -1Px;
        .leaflet-popup-tip {     width: 13Px;    height: 13Px;    Padding: 1Px;    margin: -10Px auto 0; }
    }
    a.leaflet-popup-close-button { top: 5px;  right: 3px; color: #999;}
}

// 景点弹窗样式
.senice-popup {
    width: 240px; border-radius: 6Px; background:rgba(255,255,255,.9); box-shadow: 0 0 8px 0 rgba(0,0,0,.1); 
    .hd { height:30px; line-height: 30px; padding-left: 10px; border-bottom: 1Px solid #e5e5e5; font-size: 13px;  }
    .bd { 
        overflow: hidden; padding:8px; 
        .img { float: left; display: block; width: 68px; height:68px; background:#ccc; img { width:100%; height:100%; } }
        .explain { 
            margin-left: 80px; 
            .introduction {margin:0; font-size: 11px;}
            .btns { 
                margin-top: 8px;      display: flex;     justify-content: space-between; align-items:center;
                .button { 
                    background:#ff6d00; width:47%; text-align: center; border-radius:3px; line-height: 28px; font-size: 12px; color: #fff; text-align: center;
                    i {font-size: 12px; margin-right: 5px;vertical-align: middle;}
                    .icon{display: inline-block; width:12px; height:12px; background:url('../assets/images/icon_play.png') no-repeat center center; background-size: 12px 12px;}
                    &.act .icon{background-image: url('../assets/images/icon_playing.gif');}
                    em {vertical-align: middle;}
                    &.btn-goto{background:#3f85e7;}
                }            
            }
        }
    }
}
// 服务设施弹窗
.near-services-popup{
    width:100px; padding:5px 10px; position: relative; overflow: hidden; border-radius:23px;background:rgba(255,255,255,.9);  box-shadow: 0 0 8px 0 rgba(0,0,0,.1); 
    i {display: block; width:26px; height:26px; background-size: 100% 100%; float: left;}

    span {display: block; margin-left: 30px; line-height: 26px; font-size: 14px; text-align: center;}
}
// 搜索菜单按钮 弹窗
.btn-search { position: absolute; z-index: 999; display: block; bottom: 10px;right: 10px; width: 42px; height: 42px; border-radius: 50%; background: #fff; box-shadow: 0 0 8px #999; text-align: center; line-height: 42px; font-size: 20px; }
.btn-search2 { position: absolute; z-index: 999; display: block; bottom: 62px;right: 10px; width: 42px; height: 42px; border-radius: 50%; background: #fff; box-shadow: 0 0 8px #999; text-align: center; line-height: 42px; font-size: 20px; }
.list-menu { 
    overflow: hidden; padding-top: 25px; text-align: center; 
    li { 
        float: left; width: 25%;font-size: 12px; margin-bottom: 25px; 
        &.act i { background-color: #3f85e7; color: #fff; }
        i { display: block; width: 43px;height: 43px; line-height:43px; font-size: 22px; margin: 0 auto; border: 1Px solid #ddd; border-radius: 50%;margin-bottom: 5px; background-repeat: no-repeat;background-size: 50% 50%; background-position: center;}
    }
}
</style>
